package yamen.bdwm.data;

import java.util.ArrayList;

import yamen.bdwm.data.interfaces.onListRefreshedListener;
import yamen.bdwm.datastruct.MoreAdapter;
import yamen.bdwm.datastruct.MoreAdapter.onMoreOver;
import yamen.bdwm.datastruct.WmItem;
import yamen.bdwm.datastruct.WmMoreList;
import yamen.bdwm.datastruct.WmToptenItem;
import android.os.AsyncTask;

public class WmMyToptenList extends WmMoreList {
	private String type;
	private int fromid;
	public void getRefreshed(final onListRefreshedListener mListener)
	{
		if(WmMyData.getinstance().is_iTopTen)
			type = "instant";
		else
			type = "default";
		fromid = 0;
		((MoreAdapter)adapterList.get(0)).ShowMore();
		getRefreshedForNum(type,mListener);
	}
	
	public void setItopTen(boolean isITopTen)
	{
		WmMyData.getinstance().is_iTopTen = isITopTen;
	}
	
	void getRefreshedForNum(final String type,final onListRefreshedListener mListener)
	{
		
		new AsyncTask<Void, Void, Integer>() {

			@Override
			protected Integer doInBackground(Void... params) {
				ArrayList<WmToptenItem> wms = null;
				
				if(type=="instant")
				{
					wms = WmMyData.getinstance().parser.getITopten(fromid);
					if(wms==null)return -1;
					if(fromid == 0)
						WmMyToptenList.this.list.clear();
					for(WmToptenItem i:wms)
					{
						fromid += WmMyToptenList.this.Add((WmItem)i);
					}
					return new Integer(fromid);
				}
				
				wms = WmMyData.getinstance().parser.getTopten(type);
				
				if(wms==null)return -1;
				int a = 0;
				if(type=="default")
					WmMyToptenList.this.list.clear();
				else
					a = 10;
				for(WmToptenItem i:wms)
				{
					a+=WmMyToptenList.this.Add((WmItem)i);
				}
				return new Integer(a);
			}
			
			protected void onPostExecute(Integer i)
			{
				if(i>=0)
				{
					if(i > 10 && fromid == 0 || fromid > 99)
						((MoreAdapter)adapterList.get(0)).HideMore();
					else
						((MoreAdapter)adapterList.get(0)).ShowMore();
						
					WmMyToptenList.this.NotifyAllAdapter();
					if(mListener!=null)
						mListener.onRefreshed(i);
				}
				else
				{
					if(mListener!=null)
						mListener.onError(-1);
				}
			}
		}.execute();
	}
	@Override
	protected void loadForNumber(final onMoreOver l) {
		if(fromid == 0)
			type = "more";
		else
			type = "instant";
		
		getRefreshedForNum(type,new onListRefreshedListener() {
			
			public void onRefreshed(int numberOfRefreshed) {
				l.OnMoreOver();
			}
			
			public void onError(int i) {
				l.OnMoreOver();
			}
		});
	}
}
